const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    certificates: [],
    inputValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const certificatesJson = wx.getStorageSync("certificates");
    const certificates = JSON.parse(certificatesJson);
    this.setData({
      certificates
    });
  },
  deleteCertificate: function (e) {
    const that = this;
    const certificates = that.data.certificates;
    wx.showModal({
      title: '提示',
      content: '确定删除证书？',
      success(res) {
        if (res.confirm) {
          const name = e.currentTarget.dataset.name;
          const newCertificates = certificates.filter(function (item) {
            return item !== name;
          });
          that.setData({
            certificates: newCertificates
          });
        }
      }
    })
  },
  inputValue: function (e) {
    const value = e.detail.value;
    this.setData({
      inputValue: value
    });
  },
  addCertificate: function () {
    const inputValue = this.data.inputValue;
    if (inputValue.length == 0) {
      wx.showToast({
        title: '请输入证书',
        icon: 'none'
      });
      return;
    }
    const certificates = this.data.certificates;
    if (certificates.indexOf(inputValue) >= 0) {
      wx.showToast({
        title: '已经存在此证书',
        icon: 'none'
      });
      return;
    }
    certificates.push(inputValue);
    this.setData({
      certificates,
      inputValue: ''
    });
  },
  save: function () {
    const certificates = this.data.certificates;
    if (certificates.length == 0) {
      wx.showToast({
        title: '至少输入一个证书',
        icon: 'none'
      });
      return;
    }
    const url = app.globalData.url;
    const openId = app.globalData.openId;
    wx.request({
      url: url + '/coach/updateCertificates',
      data: {
        openId,
        certificates
      },
      method: 'POST',
      success: function (response) {
        if (response.data.success) {
          wx.navigateBack({
            delta: 1
          });
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: response.data.message,
            icon: 'none'
          })
        }
      }
    })
  }
})